package cn.fl.capital.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.condition.CapPayeeInfoQueryCondition;
import cn.fl.capital.service.ICapPayeeInfoService;
import cn.fl.capital.vo.CapPayeeInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.constant.SysLogConstant;
import net.sf.json.JSONArray;

/**
 * @Description: 付款收款方信息表 控制层
 */
@Controller
@RequestMapping("/capital/capPayeeInfo")
public class CapPayeeInfoController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(CapPayeeInfoController.class);

	/**
	 * CapPayeeInfo 服务层BEAN
	 */
	@Autowired
	private ICapPayeeInfoService capPayeeInfoService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toListPage", "加载CapPayeeInfo列表页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("capital/capPayeeInfo/capPayeeInfoList");
		return mav;
	}
	
	/**
	 * 到新增页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toAddPage", "加载CapPayeeInfo Add页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("capital/capPayeeInfo/capPayeeInfoModify");
		//this.prepare(request,mav);
		return mav;
	}

	/*******************************
	 * 选择收款方账号
	 * @param request
	 * @param response
	 * @return
	 *******************************/
	@RequestMapping(value = "/toChoosePayee.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toChoosePayee(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toAddPage", "加载CapPayeeInfo Add页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("capital/capPayeeInfo/choosePayeeList");
		//this.prepare(request,mav);
		return mav;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toModifyPage", "加载CapPayeeInfo Modify页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("capital/capPayeeInfo/capPayeeInfoModify");
		//this.prepare(request,mav);
		
		String id=request.getParameter("id");
		CapPayeeInfoVO capPayeeInfoVO = this.capPayeeInfoService.selectById(Long.valueOf(id));
        mav.addObject("capPayeeInfoVO", capPayeeInfoVO);
		return mav;
	}
	
	//加载数据字典数据、传值等 ？
    public void prepare(HttpServletRequest request,ModelAndView mav){
    	
    }

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initCapPayeeInfoList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		CapPayeeInfoQueryCondition qc = new CapPayeeInfoQueryCondition();
		String searchName = request.getParameter("searchName");
		if (StringUtils.isNotEmpty(searchName)) {
			
		}
		page.setCondition(qc);

		BaseLogUtils.info(logger, "initCapPayeeInfoList", "初始化CapPayeeInfo列表页面数据.DATA:"+JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		Pager pager = this.capPayeeInfoService.searchListPage(page);
		List<CapPayeeInfoVO> list = (List<CapPayeeInfoVO>) pager.getResultList();
		ListPageVO<CapPayeeInfoVO> listPage = new ListPageVO<CapPayeeInfoVO>(list, pager.getTotalCount());
		return listPage;
	}

	/**
	 * 初始化收款方列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initPayeeList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initPayeeInfoList(HttpServletRequest request, HttpServletResponse response) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger,"initPayeeList","初始化收款方列表.开始时间：" + startTm + "-请求参数：" + this.getRequestParameter(request));
		CapPayeeInfoQueryCondition qc = new CapPayeeInfoQueryCondition();
		//收款方类型
        String payeeTypCd=request.getParameter("payeeTypCd");
		//供应商ID
        String splId=request.getParameter("splId");
		//客户ID
        String cstId=request.getParameter("cstId");
		//账户用途
		String purpCd=request.getParameter("purpCd");
		String paySchId = request.getParameter("paySchId");
		String prjPrdDtlId = request.getParameter("prjPrdDtlId");
		String orgCd = request.getParameter("orgCd");
		if(StringUtils.isNotBlank(orgCd)){
			qc.setOrgCd(orgCd);
		}
        if (StringUtils.isNotEmpty(payeeTypCd)) {
            qc.setPayeeTypCd(payeeTypCd);
        }
        if (StringUtils.isNotBlank(splId)) {
            qc.setSplId(Long.valueOf(splId));
        }
        if (StringUtils.isNotBlank(cstId)) {
            qc.setCstId(Long.valueOf(cstId));
        }
        if(StringUtils.isNotBlank(purpCd)){
        	qc.setPurpCd(purpCd);
		}
		if(StringUtils.isNotEmpty(paySchId)){
        	qc.setPaySchId(Long.parseLong(paySchId));
		}
        if(StringUtils.isNotEmpty(prjPrdDtlId)){
            qc.setPrjPrdDtlId(Long.parseLong(prjPrdDtlId));
        }

		BaseLogUtils.info(logger, "initCapPayeeInfoList", "初始化收款方列表数据.", CurrentThreadContext.getCurrentUserName());
        List<CapPayeeInfoVO> list=this.capPayeeInfoService.getPayeeList(qc);
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger,"initPayeeList","初始化收款方列表.耗时：" + (endTm - startTm) + "-返回结果：" + JSON.toJSONString(list));
        if(CollectionUtils.isNotEmpty(list)){
            return new ListPageVO<CapPayeeInfoVO>(list, list.size());
        }else{
            return null;
        }
	}


    /**
     * 查询收款方列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/getPayeeList.do", method = { RequestMethod.GET})
    @ResponseBody
    public Object getPayeeList(HttpServletRequest request, HttpServletResponse response) {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "查询成功");
        CapPayeeInfoQueryCondition qc = new CapPayeeInfoQueryCondition();
        //设置查询条件？
        String payeeTypCd=request.getParameter("payeeTypCd");//收款方类型
        String splId=request.getParameter("splId");//供应商ID
        String cstId=request.getParameter("cstId");//客户ID
        if (StringUtils.isNotEmpty(payeeTypCd)) {
            qc.setPayeeTypCd(payeeTypCd);
            if(StringUtils.isNotBlank(splId)){
                qc.setSplId(Long.valueOf(splId));
            }
            if(StringUtils.isNotBlank(cstId)){
                qc.setCstId(Long.valueOf(cstId));
            }

			List<CapPayeeInfoVO> list=this.capPayeeInfoService.getPayeeList(qc);
            if(CollectionUtils.isEmpty(list)){
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("未查到银行账户信息");
            }else{
                result.setData(JSON.toJSONString(list));
            }
        }else{
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("未知的收款方类型");
            BaseLogUtils.error(logger, "getPayeeList", "查询收款方银行账户信息出错：收款方类型为空", CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }


	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeCapPayeeInfoByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ids = request.getParameter("ids");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if (StringUtils.isEmpty(ids)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "removeCapPayeeInfoByIds", "删除CapPayeeInfo数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        List<Long> idsList = new ArrayList<Long>();
        JSONArray idsArray = JSONArray.fromObject(ids);
        for (Object object : idsArray) {
            idsList.add(Long.valueOf(object.toString()));
        }
		
		try {
			boolean success = this.capPayeeInfoService.removeByIds(idsList);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
				BaseLogUtils.info(logger, "removeCapPayeeInfoByIds", "删除CapPayeeInfo数据失败,ID:"+idsList.toString(), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "removeCapPayeeInfoByIds", "删除CapPayeeInfo数据成功,ID:"+idsList.toString(), CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "removeCapPayeeInfoByIds", "删除CapPayeeInfo数据失败,ID:"+idsList.toString()+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeCapPayeeInfoByIds", "删除CapPayeeInfo数据失败,系统错误.ID:"+idsList.toString()+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getCapPayeeInfoById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "getCapPayeeInfoById", "获取CapPayeeInfo数据,主键参数为空.", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			CapPayeeInfoVO vo = this.capPayeeInfoService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getCapPayeeInfoById", "获取CapPayeeInfo数据不存在,ID:"+id, CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getCapPayeeInfoById", "获取CapPayeeInfo数据成功,ID:"+id, CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "getCapPayeeInfoById", "获取CapPayeeInfo数据失败,ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getCapPayeeInfoById", "获取CapPayeeInfo数据失败,系统错误.ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object addCapPayeeInfo(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		CapPayeeInfoVO entity = null;//获取参数
		try {
			entity = this.getRequestParamForCapPayeeInfo(request);//获取参数
			Long id = this.capPayeeInfoService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "addCapPayeeInfo", "新增CapPayeeInfo数据成功,ID:"+id+".DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.info(logger, "addCapPayeeInfo", "新增CapPayeeInfo数据失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.error(logger, "addCapPayeeInfo", "新增CapPayeeInfo数据失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modifyCapPayeeInfo(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,SysLogConstant.LOG_CMM_UPDATE_SUCC);
		CapPayeeInfoVO entity = null;
		try {
			entity = this.getRequestParamForCapPayeeInfo(request);
			if(entity.getId()==null){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
				BaseLogUtils.info(logger, "modifyCapPayeeInfo", "修改CapPayeeInfo信息,主键参数为空！.", CurrentThreadContext.getCurrentUserName());
				return result;
			}

			boolean success = this.capPayeeInfoService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
				BaseLogUtils.info(logger, "modifyCapPayeeInfo", "修改CapPayeeInfo数据失败.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
				return result;
			}
			BaseLogUtils.info(logger, "modifyCapPayeeInfo", "修改CapPayeeInfo数据成功.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.info(logger, "modifyCapPayeeInfo", "修改CapPayeeInfo数据失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.error(logger, "modifyCapPayeeInfo", "修改CapPayeeInfo数据失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 根据 payId 获取 payeeInfoList
	 * @methodName getCapPayeeInfoListByPayId
	 * @author: liuqihao@lionbridgecapital.cn
	 * @createDate: 2019-10-16 19:48
	 * @version: V1.0.0
	 * @param request
	 * @param response
	 * @Return java.lang.Object
	 * @updateRemark [序号][YYYY-MM-DD] [更改人姓名][变更描述]
	 */
	@RequestMapping(value = "getCapPayeeInfoListByPayId.do", method = {RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public Object getCapPayeeInfoListByPayId(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String payId = request.getParameter("payId");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "查询成功");
		if (StringUtils.isEmpty(payId) || !StringUtils.isNumeric(payId)) {
			// payId为空, 不为数字类型
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("payId为数字格式且不能为空");
			return result;
		}
		List<CapPayeeInfoVO> data = null;
		try {
			CapPayeeInfoQueryCondition condition = new CapPayeeInfoQueryCondition();
			condition.setPayId(Long.valueOf(payId));
			data = this.capPayeeInfoService.searchList(condition);
			result.setData(data);
			BaseLogUtils.info(logger, "getPayeeIdListByPayId", "查询payeeId数据成功,ID:" + payId + ".DATA:" + JSON.toJSONString(data), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
			BaseLogUtils.info(logger, "getPayeeIdListByPayId", "查询payeeId数据失败.DATA:" + JSON.toJSONString(data) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
			BaseLogUtils.error(logger, "getPayeeIdListByPayId", "查询payeeId数据失败,系统错误.DATA:" + JSON.toJSONString(data) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 获取请求参数
	 * @param request 请求
	 * @return 
	 */
	private CapPayeeInfoVO getRequestParamForCapPayeeInfo(HttpServletRequest request) throws BaseException{
		//获取参数
		String id = request.getParameter("id");//主键
		String payId = request.getParameter("payId");//付款ID
		String payeeTypCd = request.getParameter("payeeTypCd");//收款方类型 1.供应商 2.承租人
		String bkId = request.getParameter("bkId");//供应商/承租人银行账户ID
		String rcptUnt = request.getParameter("rcptUnt");//收款单位/人
		String accNo = request.getParameter("accNo");//收款账号
		String actPayAmt = request.getParameter("actPayAmt");//实际付款金额
		String actPayTm = request.getParameter("actPayTm");//实际付款时间
		String fundTypCd = request.getParameter("fundTypCd");//款项：1.租赁物价款 2.保险费

		//验证参数并赋值
		CapPayeeInfoVO entity = new CapPayeeInfoVO();
 		//entity.setPayId(payId);//付款ID
 		//entity.setPayeeTypCd(payeeTypCd);//收款方类型 1.供应商 2.承租人
 		//entity.setBkId(bkId);//供应商/承租人银行账户ID
 		//entity.setRcptUnt(rcptUnt);//收款单位/人
 		//entity.setAccNo(accNo);//收款账号
 		//entity.setActPayAmt(actPayAmt);//实际付款金额
 		//entity.setActPayTm(actPayTm);//实际付款时间
 		//entity.setFundTypCd(fundTypCd);//款项：1.租赁物价款 2.保险费
	
//		if (StringUtils.isBlank(name)) {
//            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "名称不能为空.");
//      }
//      if (StringUtils.isNotBlank(num)) {
//          if (!StringUtils.isUnsignedNumeric(num)) {
//                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请填写正确的数字.");
//          }
//      }

		Date tm=new Date();
		if (StringUtils.isNotBlank(id)) {
			entity.setId(Long.valueOf(id));
			entity.setMdfTm(tm);
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
		}else{
			entity.setCrtTm(tm);
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			//entity.setCrtUsrOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前用户组织机构代码
            //entity.setOrgCd(CurrentThreadContext.getCurrentBuOrgCd());//事业部组织机构代码
		}
		
		return entity;
	}
}

